#include "UserInfoManagement.h"

#include <stdexcept>
#include <iostream>
using std::string;
using std::runtime_error;

UserInfoManagement::UserInfoManagement(const std::string& dbName,
		const std::string& ip, const unsigned int& port,
		const std::string& usr, const std::string& pwd)
: m_res(0)
{
	if (NULL == mysql_init(&m_mysql))
	{
		Release();
		throw runtime_error("mysql init failed.");
	}

	if (!mysql_real_connect(&m_mysql, ip.c_str(), usr.c_str(),
				pwd.empty()?NULL:pwd.c_str(), dbName.c_str(), port, NULL, 0))
	{
		Release();
		throw runtime_error("mysql connect failed.");
	}
}

UserInfoManagement::~UserInfoManagement()
{
	mysql_close(&m_mysql);
	Release();
}

void UserInfoManagement::Release()
{

}

QueryResult UserInfoManagement::LoginVerify(const string& usr, const string& pwd)
{
	if (usr.empty())
	{
		return USERNAME_EMPTY;
	}
	if (pwd.empty())
	{
		return PASSWORD_EMPTY;
	}

	string sqltext("select SQL_NO_CACHE Password from UserInfo where Username = '");
	char* tmpBuf = 
		new char[2 * usr.size() + 1];
	unsigned long tmpLength =
		mysql_real_escape_string(&m_mysql, tmpBuf, usr.c_str(), usr.size());
	sqltext.append(tmpBuf, tmpLength);
	sqltext += '\'';

	delete[] tmpBuf;

	if (mysql_query(&m_mysql, sqltext.c_str()))
	{
		return QUERY_FAILED;
	}

	m_res = mysql_store_result(&m_mysql);

	my_ulonglong num = mysql_num_rows(m_res); 

	if(num == 0)
	{
		mysql_free_result(m_res);
		return USERNAME_NOT_EXIST;
	}

	m_row = mysql_fetch_row(m_res);
	mysql_free_result(m_res);

	if (pwd.compare(m_row[0]) == 0)
		return SUCCESS;
	else
		return PASSWORD_ERROR;
}

QueryResult UserInfoManagement::Register(const string& usr, const string& pwd)
{
	QueryResult loginResult = LoginVerify(usr, pwd);
	char* usrName;
	char* pwdName;
	unsigned long usrNameLength, pwdNameLength;
	string sqltext;
	switch (loginResult)
	{
		case USERNAME_NOT_EXIST:
			usrName = new char[2 * usr.size() + 1];
			usrNameLength =
				mysql_real_escape_string(&m_mysql, usrName, usr.c_str(), usr.size());
			pwdName = new char[2 * pwd.size() + 1];
			pwdNameLength = 
				mysql_real_escape_string(&m_mysql, pwdName, pwd.c_str(), pwd.size());

			sqltext += "insert into UserInfo values('";
			sqltext += usrName;
			sqltext += "','";
			sqltext += pwdName;
			sqltext += "')";
			delete[] usrName;
			delete[] pwdName;

			if (mysql_query(&m_mysql, sqltext.c_str()))
			{
				return QUERY_FAILED;
			}
			return SUCCESS;
			break;
		case SUCCESS:
		case PASSWORD_ERROR:
			return USERNAME_EXIST;
		default:
			return loginResult;
	}
}
